package io.jee.runshan.handler;

import io.jee.medusa.orm.condition.Condition;
import io.jee.medusa.orm.condition.ConditionGroup;
import io.jee.runshan.domain.KeywordAsk;
import io.jee.runshan.domain.VoiceAsk;
import io.jee.runshan.domain.remote.weixin.InputMessage;
import io.jee.runshan.domain.remote.weixin.OutputTextMessage;
import io.jee.runshan.domain.remote.weixin.WeixinUserInfo;
import io.jee.runshan.service.IKeywordAskService;
import io.jee.runshan.service.IVoiceAskService;
import io.jee.runshan.service.remote.weixin.IUserInfoService;
import io.jee.runshan.utils.SpringHolder;
import io.jee.runshan.utils.WeixinConstant;

import java.util.Date;
import java.util.List;

/**
 * 关键字匹配处理
 * @author qinling.zhu
 *
 */
public class WeixinReceiverTextHandler {
	
	private IKeywordAskService keywordAskService = SpringHolder.getBean(IKeywordAskService.class);
	private IVoiceAskService voiceService = SpringHolder.getBean(IVoiceAskService.class);
	private IUserInfoService wxUserInfoService = SpringHolder.getBean(IUserInfoService.class);
	
	public String excute(InputMessage inputMsg) throws Exception {
		OutputTextMessage outputMsg = new OutputTextMessage();
		String msg = null;
		ConditionGroup group = new ConditionGroup();
		group.and(Condition.onNumber("type").eq(KeywordAsk.TYPE_FIXED));
		group.and(Condition.onText("keyword").eq(inputMsg.getContent()));
		List<KeywordAsk> list = keywordAskService.list(group);
		if (list.size() > 0) { // 说明是固定问题
			msg = list.get(0).getReplyContent();
		} else { // 关键字
			KeywordAsk keywordAsk = keywordAskService.findKeyword(inputMsg.getContent());
			WeixinUserInfo wxUserinfo = wxUserInfoService.getWeixinUserInfo(inputMsg.getFromUserName());
			VoiceAsk voiceAsk = new VoiceAsk();
			voiceAsk.setRecognition(inputMsg.getContent());
			voiceAsk.setWxOpenid(inputMsg.getFromUserName());
			voiceAsk.setType(1);
			voiceAsk.setWxNikeName(wxUserinfo.getNickname());
			voiceAsk.setPublishTime(new Date());
			
			if (keywordAsk != null) {
				msg = keywordAsk.getReplyContent();
				voiceAsk.setIsRead(1);
				voiceAsk.setReplyState(2);
			} else { // 没有匹配的内容
				msg = "您的问题我们暂时不能自动为您解答，请等待人工坐席为您服务！";
			}
			voiceService.save(voiceAsk);
		}
		outputMsg.setContent(msg);
		return WeixinConstant.genMessage(outputMsg, inputMsg);
	}
}
